package com.qf.controller;

import com.qf.entity.Friend;
import com.qf.entity.FriendApply;
import com.qf.entity.User;
import com.qf.entity.base.ResultEntity;
import com.qf.service.IFriendApplyService;
import com.qf.service.IFriendService;
import com.qf.service.api.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/15
 */
@RestController
@RequestMapping("/friendApply")
public class FriendApplyController {

    @Autowired
    private IFriendApplyService friendApplyService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFriendService friendService;

    @RequestMapping("/addFriendApply")
    public ResultEntity addFriendApply(FriendApply friendApply,String username){
        User user = userService.findUserByName(username);
        if(user.getId()==friendApply.getFid()){
            return ResultEntity.error("不能添加自己为好友");
        }
        if(user!=null){
            friendApply.setTid(user.getId());
            friendApply.setCreateTime(new Date());
            friendApply.setStatus(1);
            friendApplyService.insert(friendApply);
            return ResultEntity.successs();
        }
        return ResultEntity.error("没有找到"+username);
    }

    @RequestMapping("/getNewFriendApplyList")
    public ResultEntity getNewFriendApplyList(Integer tid){
        List<FriendApply> friendApplyList = friendApplyService.getNewFriendApplyList(tid);
        for (FriendApply friendApply : friendApplyList){
            Integer fid = friendApply.getFid();
            User user = userService.getUserById(fid);
            friendApply.setFriend(user);
        }
        return ResultEntity.successs(friendApplyList);
    }

    @RequestMapping("/updateFriendApplyStatus")
    public ResultEntity updateFriendApplyStatus(Integer status,Integer id){

        //1.根据id查询申请记录
        FriendApply friendApply = friendApplyService.selectById(id);
        friendApply.setStatus(status);
        friendApplyService.update(friendApply);

        //查询是否是好友
        Integer integer = friendService.selectIsFriend(friendApply.getTid(),friendApply.getFid());


        if(status==2){  //说明同意

            if(integer>0){  //说明已经是好友了
            } else{
                //添加好友
                friendService.addFriend(friendApply.getFid(),friendApply.getTid(),1);
                return ResultEntity.successs();
            }

        }
        return ResultEntity.error("已经是好友啦");
    }

}
